import re
import ddddocr
import requests
from typing import List
from requests_html import HTMLSession
import base64
import PySimpleGUI as sg
from ui import serach


class QianFanSo(object):
    def __init__(self):
        self.headers = {
            "authority": "pan.qianfan.app",
            "accept": "application/json, text/javascript, */*; q=0.01",
            "accept-language": "zh-CN,zh;q=0.9,zh-TW;q=0.8",
            "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
            "origin": "https://pan.qianfan.app",
            "referer": "https://pan.qianfan.app/login/",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36",
            "x-requested-with": "XMLHttpRequest"
        }
        self.base_url = "https://pan.qianfan.app/"
        self.session = HTMLSession()
        self.csrftoken = ""
        self.csrfmiddlewaretoken = ""
        self.QianFanID = ""
        self.captcha = ""
        self.name_list = []
        self.size_lsit = []
        self.url_list = []
        self.pan_list = []

    def get_csrf(self):
        url = "https://pan.qianfan.app/login/"
        response = requests.get(url, headers=self.headers)
        csrftoken = dict(response.cookies).get('csrftoken')
        csrfmiddlewaretoken = re.findall("csrfmiddlewaretoken: '(.+?)'", response.text)[0]
        self.csrftoken = csrftoken
        self.csrfmiddlewaretoken = csrfmiddlewaretoken

    def get_captcha(self):
        url = "https://api.qianfan.app/captcha/"
        params = {
            "1": ""
        }
        cookies = {
            "csrftoken": self.csrftoken
        }
        response = requests.get(url, headers=self.headers, cookies=cookies, params=params)
        QianFanID = dict(response.cookies).get('QianFanID')
        # 识别
        ocr = ddddocr.DdddOcr(beta=True)
        captcha = ocr.classification(response.content)
        self.QianFanID = QianFanID
        self.captcha = captcha

    def login_cookie(self, account: str, password: str):
        cookies = {
            "csrftoken": self.csrftoken,
            "QianFanID": self.QianFanID
        }
        url = "https://pan.qianfan.app/login/"
        data = {
            "csrfmiddlewaretoken": self.csrfmiddlewaretoken,
            "account": account,
            "pwd": password,
            "captcha": self.captcha
        }
        response = requests.post(url, headers=self.headers, cookies=cookies, data=data)
        self.QianFanID = dict(response.cookies).get('QianFanID')
        self.csrftoken = dict(response.cookies).get('csrftoken')
        cookies = {
            "csrftoken": self.csrftoken,
            "QianFanID": self.QianFanID
        }
        code = response.json().get('code')
        if code:
            return cookies
        return None

    def get_url_list(self, key: str, cookie: dict) -> List[str]:
        """

        :param key: 搜索关键字
        :return:
        """
        headers = {
            "authority": "pan.qianfan.app",
            "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
            "accept-language": "zh-CN,zh;q=0.9,en-GB;q=0.8,en;q=0.7",
            "cache-control": "no-cache",
            "pragma": "no-cache",
            "referer": "https://pan.qianfan.app/",
            "sec-ch-ua": "^\\^Google",
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": "^\\^Windows^^",
            "sec-fetch-dest": "document",
            "sec-fetch-mode": "navigate",
            "sec-fetch-site": "same-origin",
            "sec-fetch-user": "?1",
            "upgrade-insecure-requests": "1",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36"
        }
        url = "https://pan.qianfan.app/search/"
        params = {
            "pan": "all",
            "q": key
        }
        response = self.session.get(url, headers=headers, cookies=cookie, params=params)
        self.url_list = response.html.xpath('//div[@class="search-item"]/a/@href')
        self.name_list = response.html.xpath('//div[@class="search-des"]/p[1]/text()')
        self.size_list = response.html.xpath('//div[@class="search-file-size"]/text()')

    def base64_decode(self, a):
        return base64.b64decode(a.encode('utf-8')).decode('utf-8')

    def load_url(self, url, flag):
        for i in range(len(flag)):
            obj = flag[i]
            if not obj.isdigit():
                flag_num = int(obj, 16)
                url = url[:flag_num] + url[flag_num + 1:flag_num + 10000]
        return self.base64_decode(url)

    def parse_pan_url(self):
        for url in self.url_list:
            url = "https://pan.qianfan.app" + url
            res = self.session.get(url, headers=self.headers)
            data_url = res.html.xpath('//div[@class="copy-url pan-url btn-full btn"]/@data-url')[0]
            id = res.html.xpath('//div[@class="copy-url pan-url btn-full btn"]/@id')[0]
            load_url = self.load_url(data_url, id)
            self.pan_list.append(load_url)


def qf_tables_list(key_str: str, cookie: dict) -> List[List]:
    TableDatas = []
    try:
        qf = QianFanSo()
        qf.get_url_list(key_str, cookie)
        qf.parse_pan_url()
        for name, size, url in zip(qf.name_list, qf.size_list, qf.pan_list):
            size = size.split(': ')[1]
            TableDatas.append([name, size, url])
        return TableDatas
    except Exception as e:
        sg.popup_error('搜索失败！请重试', icon=serach)
